"""
收藏功能服务
"""
from typing import List, Optional
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.models.hiagent_models import AppCenterBriefInfo, ListOption, ListAppCenterFilter


class FavoriteService:
    """收藏服务类"""
    
    def __init__(self, api_client: Optional[HiAgentAPIClient] = None):
        self.api_client = api_client or HiAgentAPIClient()
    
    def add_to_favorites(self, app_id: str, workspace_id: Optional[str] = None) -> bool:
        """添加到收藏列表"""
        body = {
            "AppID": app_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            self.api_client.make_request("AddToAppCenterFavorites", body)
            return True
        except Exception:
            return False
    
    def remove_from_favorites(self, app_id: str, workspace_id: Optional[str] = None) -> bool:
        """从收藏列表移除"""
        body = {
            "AppID": app_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            self.api_client.make_request("RemoveFromAppCenterFavorites", body)
            return True
        except Exception:
            return False
    
    def list_favorites_in_homepage(
        self,
        list_opt: Optional[ListOption] = None,
        filter_opt: Optional[ListAppCenterFilter] = None,
        workspace_id: Optional[str] = None
    ) -> List[AppCenterBriefInfo]:
        """获取首页右侧收藏列表

        Note: ListFavoriteInHomePage API expects PageSize as a top-level parameter (required),
        not nested in ListOpt like other list endpoints. It also uses LastFavoriteID for pagination
        instead of Page number.
        """
        body = {}

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        # PageSize is a required top-level parameter for this endpoint
        last_favorite_id = None

        if list_opt:
            body["ListOpt"] = {
                "PageNumber": list_opt.page or 1,
                "PageSize": list_opt.page_size or 20
            }
            # Note: This endpoint doesn't use Page, it uses LastFavoriteID for pagination
            # For the first page, LastFavoriteID should be None/empty
        

        if last_favorite_id:
            body["LastFavoriteID"] = last_favorite_id

        # 设置筛选参数
        if filter_opt:
            filter_dict = {}
            if filter_opt.category_id:
                filter_dict["CategoryID"] = filter_opt.category_id
            if filter_opt.app_types:
                filter_dict["AppTypes"] = [app_type.value for app_type in filter_opt.app_types]
            if filter_opt.keyword:
                filter_dict["Keyword"] = filter_opt.keyword

            if filter_dict:
                body["Filter"] = filter_dict

        response = self.api_client.make_request("ListFavoriteAppCenter", body)
        
        apps = []
        for item in response.get("Items", []):
            from src.llm.hiagent_app.models.hiagent_models import AppType
            apps.append(AppCenterBriefInfo(
                app_id=item.get("AppID", ""),
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                category_id=item.get("CategoryID"),
                category_name=item.get("CategoryName"),
                author=item.get("Author"),
                publish_time=item.get("SubmitTime"),
                is_favorite=True,  # 收藏列表中的都是已收藏的
                usage_count=item.get("UsageCount"),
                rating=item.get("Rating")
            ))

        return apps
    
    def is_favorite(self, app_id: str, workspace_id: Optional[str] = None) -> bool:
        """检查应用是否已收藏"""
        try:
            # 通过获取应用详情来检查收藏状态
            from .app_service import AppService
            app_service = AppService(self.api_client)
            app_detail = app_service.get_app_center_detail(app_id, workspace_id)
            return app_detail.is_favorite if app_detail else False
        except Exception:
            return False